import { getName } from '@/api/utils';
import React, { memo, useEffect, useRef, useState } from 'react';
import { CSSTransition } from 'react-transition-group';
import { prefixStyle, formatPlayTime } from '@/api/utils';

// 引入的代码
import animations from 'create-keyframe-animation';
import ProgressBar from '@/baseUI/progress-bar';
import {
  NormalPlayerContainer,
  Top,
  Middle,
  Bottom,
  Operators,
  CDWrapper,
  ProgressWrapper,
} from './style';
import { playMode } from '@/api/config';
export default memo(function NormalPlayer(props) {
  const {
    song,
    fullScreen,
    playing,
    percent,
    duration,
    currentTime,
    mode,
  } = props;
  const {
    toggleFullScreen,
    clickPlaying,
    onProgressChange,
    handlePrev,
    handleNext,
    changeMode,
  } = props;
  const normalPlayerRef = useRef();
  const cdWrapperRef = useRef();
  const [isOverWidth, setIsOverWidth] = useState(false);
  const transform = prefixStyle('transform');
  const TITLE_WIDTH = 290;
  const { togglePlayList } = props;
  //计算偏移的辅助函数获取 miniPlayer 图片中心相对 normalPlayer 唱片中心的偏移
  const _getPosAndScale = () => {
    // miniplayer 图片的宽度
    const miniPlayerImgWidth = 40;
    const paddingLeft = 40;
    const paddingBottom = 30;
    const paddingTop = 80;
    // window.innerWidth 是屏幕的宽度 当时设置的唱片的宽度是 window.innerWidth * 0.8
    const CDPlayerImgWidth = window.innerWidth * 0.8;
    const scale = miniPlayerImgWidth / CDPlayerImgWidth;
    // 两个圆心的横坐标距离和纵坐标距离
    const x = -(window.innerWidth / 2 - paddingLeft);
    const y =
      window.innerHeight - paddingTop - CDPlayerImgWidth / 2 - paddingBottom;
    return {
      x,
      y,
      scale,
    };
  };
  // 启用帧动画
  const enter = () => {
    normalPlayerRef.current.style.display = 'block';
    const { x, y, scale } = _getPosAndScale(); // 获取 miniPlayer 图片中心相对 normalPlayer 唱片中心的偏移
    const animation = {
      0: {
        transform: `translate3d(${x}px,${y}px,0) scale(${scale})`,
      },
      60: {
        transform: `translate3d(0, 0, 0) scale(1.1)`,
      },
      100: {
        transform: `translate3d(0, 0, 0) scale(1)`,
      },
    };
    animations.registerAnimation({
      name: 'move',
      animation,
      presets: {
        duration: 400,
        easing: 'linear',
      },
    });
    animations.runAnimation(cdWrapperRef.current, 'move');
  };
  const afterEnter = () => {
    // 进入后解绑帧动画
    const cdWrapperDom = cdWrapperRef.current;
    animations.unregisterAnimation('move');
    cdWrapperDom.style.animation = '';
  };
  const leave = () => {
    if (!cdWrapperRef.current) return;
    const cdWrapperDom = cdWrapperRef.current;
    cdWrapperDom.style.transition = 'all 0.4s';
    const { x, y, scale } = _getPosAndScale();
    cdWrapperDom.style[
      transform
    ] = `translate3d (${x}px, ${y}px, 0) scale (${scale})`;
  };

  const afterLeave = () => {
    if (!cdWrapperRef.current) return;
    const cdWrapperDom = cdWrapperRef.current;
    cdWrapperDom.style.transition = '';
    cdWrapperDom.style[transform] = '';
    // 一定要注意现在要把 normalPlayer 这个 DOM 给隐藏掉，因为 CSSTransition 的工作只是把动画执行一遍
    // 不置为 none 现在全屏播放器页面还是存在
    normalPlayerRef.current.style.display = 'none';
  };
  const getPlayMode = () => {
    let content;
    if (mode === playMode.sequence) {
      content = '&#xe625;';
    } else if (mode === playMode.loop) {
      content = '&#xe653;';
    } else {
      content = '&#xe61b;';
    }
    return content;
  };

  useEffect(() => {
    let text = document.getElementById('songName');
    const template = `<span id='songName'>${song.name}</span>`;
    let divNode = document.createElement('div');
    divNode.innerHTML = template;
    document.body.appendChild(divNode);
    text = document.getElementById('songName');
    if (text.offsetWidth > TITLE_WIDTH) {
      setIsOverWidth(true);
    } else if (text.offsetWidth < TITLE_WIDTH) {
      setIsOverWidth(false);
    }
    text.remove();
  }, [fullScreen, song]);
  return (
    <CSSTransition
      classNames="normal"
      in={fullScreen}
      mountOnEnter
      timeout={400}
      onEnter={enter}
      onEntered={afterEnter}
      onExit={leave}
      onExited={afterLeave}
    >
      <NormalPlayerContainer ref={normalPlayerRef}>
        <div className="background">
          <img
            src={song.al.picUrl + '?param=300x300'}
            alt="歌曲图片"
            width="100%"
            height="100%"
          />
        </div>
        <div className="background layer"></div>
        <Top className="top">
          <div
            className="back"
            onClick={() => {
              toggleFullScreen(false);
            }}
          >
            <i className="iconfont icon-back">&#xe662;</i>
          </div>
          <h1 className="title">
            {isOverWidth ? (
              <div className="scroll-area">
                <div className="scroll">
                  <span className="today-scroll-content">{song.name}</span>
                  <span className="today-scroll-content"> {song.name}</span>
                </div>
              </div>
            ) : (
              <span>{song.name}</span>
            )}
          </h1>
          <h1 className="subtitle">
            <span>{getName(song.ar)}</span>
          </h1>
        </Top>
        <Middle ref={cdWrapperRef}>
          <CDWrapper>
            <div className="cd">
              <img
                className={`image play ${playing ? '' : 'pause'}`}
                src={song.al.picUrl + '?param=400x400'}
                alt=""
              />
            </div>
          </CDWrapper>
        </Middle>
        <Bottom className="bottom">
          <ProgressWrapper>
            <span className="time time-l">{formatPlayTime(currentTime)}</span>
            <div className="progress-bar-wrapper">
              <ProgressBar
                percent={percent}
                percentChange={onProgressChange}
              ></ProgressBar>
            </div>
            <div className="time time-r">{formatPlayTime(duration)}</div>
          </ProgressWrapper>
          <Operators>
            <div className="icon i-left" onClick={changeMode}>
              <i
                className="iconfont"
                dangerouslySetInnerHTML={{
                  __html: getPlayMode(),
                }}
              ></i>
            </div>
            <div className="icon i-left" onClick={handlePrev}>
              <i className="iconfont">&#xe6e1;</i>
            </div>
            <div className="icon i-center">
              <i
                className="iconfont"
                onClick={(e) => clickPlaying(e, !playing)}
                dangerouslySetInnerHTML={{
                  __html: playing ? '&#xe723;' : '&#xe731;',
                }}
              ></i>
            </div>
            <div className="icon i-right" onClick={handleNext}>
              <i className="iconfont">&#xe718;</i>
            </div>
            <div className="icon i-right" onClick={() => togglePlayList(true)}>
              <i className="iconfont">&#xe640;</i>
            </div>
          </Operators>
        </Bottom>
      </NormalPlayerContainer>
    </CSSTransition>
  );
});
